package com.danceforyou.user.controller;

import com.danceforyou.common.model.view.BizData4Page;
import com.danceforyou.common.restful.exception.BizExceptionEnum;
import com.danceforyou.common.service.OperationService;
import com.danceforyou.common.util.AssertUtil;
import com.danceforyou.common.util.Constants;
import com.danceforyou.common.util.OSUtils;
import com.danceforyou.common.util.StringUtil;
import com.danceforyou.common.model.ConfigDO;
import com.danceforyou.common.service.ConfigService;
import com.danceforyou.common.vo.SqlOrderEnum;
import com.danceforyou.user.model.RoleDO;
import com.danceforyou.user.model.UserDO;
import com.danceforyou.user.service.MenuService;
import com.danceforyou.user.service.RoleService;
import com.danceforyou.user.service.UserService;
import com.danceforyou.user.vo.MenuVO;
import com.danceforyou.user.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private ConfigService configService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private OperationService operationService;
    @Autowired(required = false)
    private HttpSession session;

    /**
     * 员工登录
     * @param account 账号
     * @param password 密码
     * @param request HttpServletRequest
     * @return boolean
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public boolean login(String account, String password, HttpServletRequest request) {
        //获取IP白名单配置
        ConfigDO config = configService.getByProperty("configText", Constants.CONFIG_IP_WHITE_LIST);
        //IP白名单校验
        boolean isWhiteIp = false;
        String requestIP = OSUtils.getRemoteHost(request);
        if (config == null || StringUtil.isBlank(config.getConfigValue())) {
            isWhiteIp = true;
        } else {
            String[] whiteIpList = config.getConfigValue().split(",");
            app : for (String whiteIp : whiteIpList) {
                String[] requestIPV4 = requestIP.split("\\.");
                String[] whiteIpV4 = whiteIp.split("\\.");
                AssertUtil.isTrue(requestIPV4.length == 4, "未授权的访问IP");
                AssertUtil.isTrue(whiteIpV4.length == 4, "系统配置信息错误");
                for (int i=0; i<4; i++) {
                    if (!whiteIpV4[i].equals("*") && !whiteIpV4[i].equals(requestIPV4[i])) {
                        isWhiteIp = true;
                        break app;
                    }
                }
            }
        }
        AssertUtil.isTrue(isWhiteIp, "未授权的访问IP");
        //登录
        userService.saveLogin(account, password, requestIP);
        return true;
    }

    /**
     * 员工退出登录
     * @return boolean
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public boolean logout() {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        if (loginUser != null) {
            session.removeAttribute(Constants.SESSION_USER);
            operationService.saveOperation(Constants.OPER_TABLE_USER, loginUser.getId(), Constants.OPER_LOGOUT, loginUser, null);
        }
        return true;
    }

    /**
     * 获取登录员工信息
     * @return UserVO
     */
    @RequestMapping(value = "/getLoginInfo", method = RequestMethod.GET)
    public UserVO getLoginInfo() {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        return loginUser;
    }

    /**
     * 获取员工菜单列表
     * @return List<MenuVO>
     */
    @RequestMapping(value = "/getUserMenus", method = RequestMethod.GET)
    public List<MenuVO> getUserMenus() {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        return menuService.getUserMenus(loginUser.getId());
    }

    /**
     * 分页查询员工列表
     * @param bizData4Page BizData4Page
     * @return BizData4Page
     */
    @RequestMapping(value = "/queryUserPage", method = RequestMethod.GET)
    public BizData4Page<UserVO> queryUserPage(BizData4Page<UserVO> bizData4Page) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        Map<String, Object> condition = bizData4Page.getCondition();
        for (Map.Entry<String, Object> entry : condition.entrySet()) {
            if (StringUtil.isBlank(entry.getValue().toString())) {
                condition.put(entry.getKey(), null);
            }
        }
        condition.put("isDelete", 0);
        userService.queryPageByDataPerm(bizData4Page);
        return bizData4Page;
    }

    /**
     * 新建员工
     * @param user 员工信息
     * @return boolean
     */
    @RequestMapping(value = "/saveUserInfo", method = RequestMethod.POST)
    public boolean saveUserInfo(UserDO user) {
        userService.saveUserInfo(user);
        return true;
    }

    /**
     * 修改员工
     * @param user 员工信息
     * @return boolean
     */
    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
    public boolean updateUserInfo(UserDO user) {
        userService.updateUserInfo(user);
        return true;
    }

    /**
     * 删除员工
     * @param ids 员工IDS
     * @return boolean
     */
    @RequestMapping(value = "/deleteUserInfoByIds", method = RequestMethod.POST)
    public boolean deleteUserInfoByIds(String ids) {
        userService.deleteUserInfoByIds(ids);
        return true;
    }

    /**
     * 停用员工
     * @param userId 员工ID
     * @return boolean
     */
    @RequestMapping(value = "/setUserDisable", method = RequestMethod.POST)
    public boolean setUserDisable(Long userId) {
        userService.setUserDisable(userId);
        return true;
    }

    /**
     * 启用员工
     * @param userId 员工ID
     * @return boolean
     */
    @RequestMapping(value = "/setUserEnable", method = RequestMethod.POST)
    public boolean setUserEnable(Long userId) {
        userService.setUserEnable(userId);
        return true;
    }

    /**
     * 重置员工密码
     * @param userId 员工ID
     * @return boolean
     */
    @RequestMapping(value = "/setUserPasswordReset", method = RequestMethod.POST)
    public boolean setUserPasswordReset(Long userId) {
        userService.setUserPasswordReset(userId);
        return true;
    }

    /**
     * 修改员工密码
     * @param oldPassword 原密码
     * @param newPassword 新密码
     * @return boolean
     */
    @RequestMapping(value = "/updateUserPassword", method = RequestMethod.POST)
    public boolean updateUserPassword(String oldPassword, String newPassword) {
        userService.updateUserPassword(oldPassword, newPassword);
        return true;
    }

    /**
     * 获取部门用户列表
     * @param roleCode 部门类型
     * @return List<UserDO>
     */
    @RequestMapping(value = "/listUserByRoleCode", method = RequestMethod.GET)
    public List<UserDO> listUserByRoleCode(String roleCode) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        List<Long> roleIdList = new ArrayList<>();
        switch (roleCode) {
            case Constants.ROLE_GLB_CODE:
                roleIdList.add(Constants.ROLE_GLB_ID);
                break;
            case Constants.ROLE_MJB_CODE:
                roleIdList.add(Constants.ROLE_MJB_ID);
                break;
            case Constants.ROLE_XSB_CODE:
                roleIdList.add(Constants.ROLE_XSB_ID);
                break;
            case Constants.ROLE_CWB_CODE:
                roleIdList.add(Constants.ROLE_CWB_ID);
                break;
            case "ALL":
                roleIdList.add(Constants.ROLE_GLB_ID);
                roleIdList.add(Constants.ROLE_MJB_ID);
                roleIdList.add(Constants.ROLE_XSB_ID);
                roleIdList.add(Constants.ROLE_CWB_ID);
                break;
            default:
                break;
        }
        for (int i=0; i<roleIdList.size(); i++) {
            Long roleId = roleIdList.get(i);
            List<RoleDO> subRoleList = roleService.listByProperty("pId", roleId);
            for (RoleDO subRole : subRoleList) {
                roleIdList.add(subRole.getId());
            }
        }
        Map<String, Object> condition = new HashMap<>();
        condition.put("isDelete", false);
        condition.put("roleIdList", roleIdList);
        return userService.listByCondition(condition, "id", SqlOrderEnum.ASC);
    }

    /**
     * 获取下级员工雷暴
     * @param hasSelf 是否包含自己
     * @return List<UserDO>
     */
    @RequestMapping(value = "/listSubUser", method = RequestMethod.GET)
    public List<UserDO> listSubUser(Boolean hasSelf) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        List<UserDO> userList = new ArrayList<>();
        if (hasSelf != null && hasSelf) {
            userList.add(loginUser);
        }
        List<RoleDO> roleList = new ArrayList<>(roleService.listByProperty("pId", loginUser.getRole().getId()));
        while (!roleList.isEmpty()) {
            userList.addAll(userService.listByProperty("roleId", roleList.get(0).getId()));
            roleList.remove(0);
        }
        return userList;
    }

    /**
     * 根据客户ID获取所有员工
     * @param customerId 客户ID
     * @return List<UserVO>
     */
    @RequestMapping(value = "/listAllUsersByCustomerId", method = RequestMethod.GET)
    public List<UserVO> listAllUsersByCustomerId(Long customerId) {
        return userService.listAllUsersByCustomerId(customerId);
    }
}
